<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body style="margin-top: 20px" :title="'文件管理器'" width="980px" @close="close">
    <div class="explorer-container no-background-container auto-height-container">
      <el-row :gutter="20">
        <!--<el-col :lg="4" :md="24" :sm="24" :xl="4" :xs="24">
          <vab-card class="auto-height-card">
            <el-input v-model="filterText" placeholder="请输入查询条件" style="margin-bottom: 10px" />
            <el-tree
              ref="treeRef"
              :data="data"
              default-expand-all
              :filter-node-method="filterNode"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
              <template #default="{ node }">
                <el-icon>
                  <folder />
                </el-icon>
                <span style="margin-left: 3px">{{ node.label }}</span>
              </template>
            </el-tree>
          </vab-card>
        </el-col>-->
        <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
          <vab-card class="auto-height-card">
            <vab-query-form>
              <vab-query-form-top-panel>
                <el-form inline label-width="49px" :model="queryForm" @submit.prevent>
                  <el-form-item label="标题">
                    <el-input v-model="queryForm.key" clearable placeholder="请输入标题" />
                  </el-form-item>
                  <el-form-item>
                    <el-button :icon="Search" :loading="listLoading" native-type="submit" type="primary" @click="queryData">查询</el-button>
                  </el-form-item>
                </el-form>
              </vab-query-form-top-panel>
              <vab-query-form-left-panel :span="24">
                <el-upload
                  :action="baseurl + 'base/upload'"
                  multiple
                  name="upload_image"
                  :on-error="fetchData"
                  :on-success="OnSuccess"
                  :show-file-list="false"
                  style="margin: 0 10px 10px 0"
                >
                  <el-button :icon="Upload" type="primary">本地上传</el-button>
                </el-upload>
                <el-button :icon="Delete" type="danger" @click="handleDelete">删除</el-button>
              </vab-query-form-left-panel>
            </vab-query-form>
            <el-row v-loading="listLoading" class="explorer-image-box" :gutter="20">
              <el-col v-for="(item, index) in list" :key="index" :lg="6" :md="8" :sm="12" :xl="6" :xs="12">
                <vab-card :body-style="{ padding: '0', position: 'relative' }">
                  <el-checkbox v-model="item.checked" :label="item.name" @change="handleCheckboxChange($event, item)" />
                  <el-image :preview-src-list="previewSrcList" preview-teleported :src="item.url" />
                  <div style="padding: 10px; text-align: center">{{ item.name }}</div>
                </vab-card>
              </el-col>

              <el-col v-if="list.length === 0" :span="24">
                <el-empty class="vab-data-empty" description="暂无数据" />
              </el-col>
            </el-row>

            <vab-pagination
              :current-page="queryForm.page"
              :page-size="queryForm.page_num"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </vab-card>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <el-button type="info" @click="close">取消</el-button>
      <el-button type="primary" @click="used">确定</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
import { Delete, Search, Upload } from '@element-plus/icons-vue'
import { ElLoading, ElMessage, ElTree } from 'element-plus'
import { api_getFileList, api_upload_base64, api_upload_file } from '/@/api/files'
import { api_datalist, api_del, api_delChecked } from '/@/api/obj'

//组建说明：本组建用于上传图片使用。
//出现打包后无法上传图片情况时候

//第一步：node_modules\mockjs\dist\mock.js
//搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;
//第二步：\node_modules\mockjs\src\mock\xhr\xhr.js
//搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;

defineOptions({
  name: 'FilesExplorer',
})

const emit = defineEmits(['get-files'])
//使用图片
const used = (row: any) => {
  if (selectRows.value.length > 0) {
    console.log(selectRows.value)
    const ids = selectRows.value.map((item: any) => item).join()

    //获取文件列表
    api_getFileList({ ids: ids }).then((res: any) => {
      close(res.datalist)
    })
  } else {
    $baseMessage('您未选中任何图片', 'warning', 'hey')
  }
}

//选择图片
const handleCheckboxChange = (checked: any, item: any) => {
  console.log('选择图片', item)
  console.log('list', list)
  if (checked) selectRows.value.push(item.id)
  else {
    const index = selectRows.value.findIndex((item: any) => item === item.id)
    selectRows.value.splice(index, 1)
  }
  console.log(selectRows)
}

//上传成功
const OnSuccess = (res: any, file: any) => {
  console.log('上传成功', res)
  if (res.code == 200) {
    //表示上传成功，向files_file文件里插入
    res.data.name = file.name
    api_upload_file(res.data).then((r: any) => {
      queryForm.page = 1
      fetchData()
    })
  }
}

const $baseConfirm = inject<any>('$baseConfirm')
const $baseMessage = inject<any>('$baseMessage')
const list = ref<any>([])
const listLoading = ref<boolean>(true)
const total = ref<any>(0)
const selectRows = ref<any>([])
const baseurl = `${import.meta.env.VITE_APP_BASE_URL}`
const queryForm = reactive<any>({
  page: 1,
  page_num: 20,
})
const filterText = ref<string>('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const previewSrcList = ref<any>([])
const dialogFormVisible = ref<boolean>(false)

//---------------------------
//图片组建粘贴
const uploadRef = ref<any>(null)
//初始化粘贴准备
const startPasteProcess = () => {
  console.log('资源库请粘贴内容')
  window.addEventListener('paste', handlePaste) // 监听粘贴事件
}
//粘贴操作
const handlePaste = (event: ClipboardEvent) => {
  const items = (event.clipboardData || (event as any).originalEvent.clipboardData).items

  if (!items || items.length === 0) {
    ElMessage({
      message: '当前浏览器不支持本地',
      type: 'error',
    })
    return
  }

  let file = ''
  // 搜索剪切板items
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      file = items[i].getAsFile()
      break
    }
  }
  if (!file) {
    // ElMessage({
    //   message: '粘贴内容非图片',
    //   type: 'warning',
    // })
    return
  }
  convertToBase64(file, (base64Str: any) => {
    uploadFile(base64Str)
  })
}
//粘贴转base64
const convertToBase64 = (file: any, callback: any) => {
  const reader = new FileReader()
  reader.onload = (event) => {
    callback(event.target.result)
  }
  reader.readAsDataURL(file)
}
//进行粘贴上传
const uploadFile = (base64Str: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  console.log('上传前', base64Str)
  api_upload_base64({ img: base64Str }).then((res: any) => {
    console.log('上传后', res)
    loading.close()
    if (res.code == 200) {
      //表示上传成功，向files_file文件里插入
      api_upload_file(res).then((r: any) => {
        queryForm.page = 1
        fetchData()
      })
    }
  })
}

//通用显示弹窗
const showDialog = (res: any) => {
  fetchData()
  dialogFormVisible.value = true
  startPasteProcess()
}
defineExpose({
  showDialog,
})

watch(filterText, (value) => {
  treeRef.value?.filter(value)
})

const handleNodeClick = () => {
  fetchData()
}

const defaultProps = {
  children: 'children',
  label: 'label',
}
//通用关闭弹窗
const close = (files: any) => {
  selectRows.value = []
  list.value = []
  dialogFormVisible.value = false
  window.removeEventListener('paste', handlePaste)
  console.log('资源库移出粘贴')
  emit('get-files', files)
}
//获取所有数据
const fetchData = async () => {
  selectRows.value = []
  listLoading.value = true
  const { datalist, num } = await api_datalist('files_file', queryForm)
  if (datalist) {
    list.value = datalist
    total.value = num
    previewSrcList.value = datalist.map((item: any) => item.url)
    listLoading.value = false
  }
}

//修改单页多少条
const handleSizeChange = (value: number) => {
  queryForm.page = 1
  queryForm.page_num = value
  fetchData()
}

//翻页
const handleCurrentChange = (value: number) => {
  queryForm.page = value
  fetchData()
}

//搜索查询
const queryData = () => {
  queryForm.page = 1
  fetchData()
}

//删除图片
const handleDelete = (row: any) => {
  if (row.id) {
    $baseConfirm('您确定要删除当前项吗', null, async () => {
      const { msg }: any = await api_del('files_file', { ids: row.id })
      $baseMessage(msg, 'success', 'hey')
      await fetchData()
    })
  } else {
    if (selectRows.value.length > 0) {
      console.log(selectRows.value)
      const ids = selectRows.value.map((item: any) => item).join()
      $baseConfirm('您确定要删除选中项吗', null, async () => {
        const { msg }: any = await api_delChecked('files_file', { ids: ids })
        $baseMessage(msg, 'success', 'hey')
        await fetchData()
        selectRows.value = []
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}

//加载所有图片
onBeforeMount(() => {
  // fetchData()
})

const filterNode: any = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

interface Tree {
  id: number
  label: string
  children?: Tree[]
}
//分类数据
const data: Tree[] = [
  {
    id: 1,
    label: '一级 1',
    children: [
      {
        id: 4,
        label: '二级 1-1',
        children: [
          {
            id: 9,
            label: '三级 1-1-1',
          },
          {
            id: 10,
            label: '三级 1-1-2',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: '一级 2',
    children: [
      {
        id: 5,
        label: '二级 2-1',
      },
      {
        id: 6,
        label: '二级 2-2',
      },
    ],
  },
  {
    id: 3,
    label: '一级 3',
    children: [
      {
        id: 7,
        label: '二级 3-1',
      },
      {
        id: 8,
        label: '二级 3-2',
      },
    ],
  },
]
</script>

<style lang="scss" scoped>
.explorer-container {
  .explorer-image-box {
    flex: 1;
    overflow-y: auto;

    :deep() {
      .el-card__body {
        &:hover {
          .el-image {
            scale: 1.1;
          }
        }

        .el-image {
          width: 100%;
          height: 180px;
          transition: all ease-in-out 0.3s !important;
          scale: 1.05;
        }

        .el-checkbox {
          position: absolute;
          top: 5px;
          left: 10px;
        }
      }
    }
  }
}
</style>
